<template>
  <avue-crud class="processTable" :option="option" :table-loading="loading" :data="data" ref="crud" v-model="form" :span-method="spanMethod" @row-del="rowDel" @row-update="rowUpdate" @row-save="rowSave" :before-open="beforeOpen" @selection-change="selectionChange" @refresh-change="refreshChange" @on-load="onLoad">
    <template slot="menuRight">
      <table-right :crud="$refs.crud" :data="data" :searchBtn="false" :columnBtn="true" :addPermission="addBtn&&this.productId" :handleDelete="handleDelete" :delPermission="permission.process_remove" :refreshChange="refreshChange">
      </table-right>
    </template>
    <template slot-scope="{scope,row}" slot="menuForm">
      <el-button icon="el-icon-circle-plus" v-if="type=='add'" v-loading="goon" size="mini" plain type="primary" @click.stop="saveAndGoon()">保存并继续</el-button>
    </template>
    <template slot-scope="{ row }" slot="procedureId">
      {{ row.procedureName }}
    </template>
    <!-- <template slot-scope="{ row }" slot="equipmentNo">
        {{ row.equipmentName }}
      </template> -->
    <template slot-scope="{ row }" slot="produceLineId">
      {{ row.produceLineName }}
    </template>
    <template slot-scope="{ row }" slot="produceShopId">
      {{ row.produceShopName }}
    </template>

    <template slot-scope="{ row }" slot="groupIdsForm">
      <el-select :disabled="dialogOpenType=='view'" size="small" multiple v-model="row.groupIds" style="width:100%" placeholder="请选择 生产班组">
        <el-option v-for="item in groupIdsList" :key="item.id" :label="item.team" :value="item.id">
        </el-option>
      </el-select>
    </template>
    <template slot-scope="{ row }" slot="prdList">
      <div class="prdList">
        <div class="prdItem" v-for="(item,index) in row.equipmentNameList" :key="index">{{item}}</div>
      </div>
    </template>
    <template slot-scope="{ row }" slot="mouldList">
      <div class="prdList">
        <div class="prdItem" v-for="(item,index) in row.mouldNameList" :key="index">{{item}}</div>
      </div>
    </template>
    <template slot-scope="{ row }" slot="prdProcedureFixtureList">
      <div class="prdList">
        <div class="prdItem" v-for="(item,index) in row.fixtureNameList" :key="index">{{item}}</div>
      </div>
    </template>

    <template slot="equipmentNoForm" slot-scope="{row}">
      <el-select size="small" :disabled="dialogOpenType=='view'" v-model="row.equipmentNo" style="width:100%" filterable @change="equipmentChange(row)">
        <el-option v-for="item in equipmentOption" :key="item.equipmentNo" :label="item.label" :value="item.equipmentNo">
        </el-option>
      </el-select>
    </template>
    <template slot="mouldNoListForm" slot-scope="{row}">
      <el-select size="small" :disabled="dialogOpenType=='view'" v-model="row.mouldNoList" multiple filterable style="width:100%">
        <el-option v-for="item in row.mouldOption" :key="item.equipment_no" :label="item.equipment_name" :value="item.equipment_no">
        </el-option>
      </el-select>
    </template>
    <template slot-scope="{ row }" slot="menu">
      <el-tooltip class="item" effect="dark" content="查看" placement="bottom">
        <el-button icon="el-icon-view" size="small" type="text" @click.stop="$refs.crud.rowView(row, row.$index)" v-if="viewBtn"></el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
        <el-button icon="el-icon-edit" size="small" type="text" @click.stop="$refs.crud.rowEdit(row, row.$index)" v-if="editBtn"></el-button>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
        <el-button icon="el-icon-delete" size="small" type="text" @click.stop="rowDel(row)" v-if="delBtn"></el-button>
      </el-tooltip>
    </template>
  </avue-crud>
</template>

<script>
import {
  getProProcessList,
  addProProcess,
  removeProProcess,
  updateProProcess,
  getProProcess,
  getProdMouldList,
  getProdequipmentList,
  getEquipmentList,
  getProdFixtureList,
  getGroupList,
} from '@/api/project/productData/processData';
import { masterProducts } from '@/api/project/productData/product';
import { getWorkshopList, getLines } from '@/api/project/productData/baseData';
import { getProcessList } from '@/api/project/productData/baseData';
import { mapGetters } from 'vuex';
import { numParseReg, numFloor } from '@/util/zhengze';

import { init } from '@/mixins/init';
export default {
  mixins: [init],
  props: {
    addBtn: {
      type: Boolean,
    },
    viewBtn: {
      type: Boolean,
    },
    editBtn: {
      type: Boolean,
    },
    delBtn: {
      type: Boolean,
    },
    productId: {
      type: String,
    },
    materialName: {
      type: String,
    },
    innerDrawingNo: {
      type: String,
    },
    materialNo: {
      type: String,
    },
    type: {
      type: String,
    },
  },
  data() {
    return {
      dialogOpenType: '',
      equipmentOption: [],
      produceShopList: [],
      groupIdsList: [],
      option: {
        dialogHeight: '100%',
        dialogWidth: '1000',
        page: false,
        tip: false,
        border: true,
        index: true,
        indexLabel: '序号',
        selection: true,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        addBtn: false,
        menuWidth: 100,
        header: true,
        menu: true,
        columnBtn: true,
        filterBtn: true,
        // dialogTop: "10%",
        dialogTop: 155,
        dialogClickModal: false,
        column: [
          // {
          //   label: '产品名称',
          //   prop: 'materialName',
          //   disabled: true,
          //   editDisplay: false,
          //   viewDisplay: false,
          //   span: 8,
          //   hide: true,
          //   showColumn: false,
          // },
          // {
          //   label: '产品图号',
          //   prop: 'innerDrawingNo',
          //   disabled: true,
          //   editDisplay: false,
          //   viewDisplay: false,
          //   span: 8,
          //   hide: true,
          //   showColumn: false,
          // },
          // {
          //   label: '产品编码',
          //   prop: 'materialNo',
          //   disabled: true,
          //   editDisplay: false,
          //   viewDisplay: false,
          //   span: 8,
          //   hide: true,
          //   showColumn: false,
          // },
          // {
          //   labelWidth: 0,
          //   label: '',
          //   prop: 'info',
          //   span: 24,
          //   hide: true,
          //   formslot: true,
          //   addDisplay: true,
          //   editDisplay: false,
          //   viewDisplay: false,
          // },
          {
            label: '工艺',
            prop: 'craftType',
            span: 12,
            type: 'select',
            dicUrl: '/api/blade-system/dict-biz/dictionary?code=craft',
            cascaderItem: ['procedureId'],
            props: {
              label: 'dictValue',
              value: 'dictKey',
            },
            rules: [
              {
                required: true,
                message: '请选择工艺',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '工序名称',
            prop: 'procedureId',
            editDisplay: true,
            viewDisplay: true,
            filterable: true,
            slot: true,
            type: 'select',
            minWidth: 120,
            dicUrl: '/api/hg-public/procedure/list?craftType={{craftType}}',
            props: {
              label: 'name',
              value: 'id',
            },
            span: 12,
            rules: [
              {
                required: true,
                message: '请选择工序名称',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '生产车间',
            prop: 'produceShopId',
            slot: true,
            // addDisplay: false,
            editDisplay: true,
            viewDisplay: true,
            minWidth: 130,
            span: 12,
            type: 'select',
            dicData: [],
            cascaderItem: ['groupIds'],
            // dicUrl: '/api/blade-system/dict-biz/dictionary?code=projectType',
            props: {
              label: 'deptName',
              value: 'id',
            },
            rules: [
              {
                required: true,
                message: '请选择车间名称',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '生产线',
            prop: 'produceLineId',
            span: 12,
            minWidth: 130,
            // addDisplay: false,
            editDisplay: true,
            viewDisplay: true,
            slot: true,
            type: 'select',
            dicData: [],
            // dicUrl: '/api/blade-system/dict-biz/dictionary?code=projectType',
            props: {
              label: 'name',
              value: 'id',
            },
            rules: [
              {
                required: true,
                message: '请选择生产线',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '生产班组',
            prop: 'groupIds',
            showColumn: false,
            // addDisplay: false,
            editDisplay: true,
            viewDisplay: true,
            minWidth: 130,
            span: 12,
            type: 'select',
            formslot: true,
            multiple: true,
            dicData: [],
            dicUrl: '/api/hg-public/prdprocedure/getGroupList?produceShopId={{produceShopId}}',
            props: {
              label: 'team',
              value: 'id',
            },
            // rules: [
            //   {
            //     required: true,
            //     message: '请选择生产班组',
            //     trigger: 'blur',
            //   },
            // ],
          },
          {
            label: '生产节拍',
            prop: 'produceBeat',
            span: 12,
            // addDisplay: false,
            editDisplay: true,
            viewDisplay: true,
            minWidth: 130,
            maxlength: 6,
            overHidden: true,
            append: '秒',
            rules: [
              {
                required: true,
                message: '请输入生产节拍',
                trigger: 'blur',
              },
              {
                pattern: numFloor,
                message: '只能为正整数（不包含0）或最多两位小数',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '设备清单',
            prop: 'prdProcedureEquipments',
            type: 'dynamic',
            // addDisplay: false,
            editDisplay: true,
            viewDisplay: true,
            span: 24,
            children: {
              align: 'center',
              headerAlign: 'center',
              column: [
                {
                  label: '设备名称',
                  prop: 'equipmentNo',
                  formslot: true,
                  filterable: true,
                  type: 'select',
                  minWidth: 120,
                  dicData: [],
                  props: {
                    label: 'equipmentName',
                    value: 'equipmentNo',
                  },
                  span: 24,
                },
                // {
                //   label: "设备数量",
                //   prop: "equipmentNum",
                //   maxlength: 5
                // },
                {
                  label: '模具',
                  prop: 'mouldNoList',
                  type: 'select',
                  formslot: true,
                  minWidth: 120,
                  dicData: [],
                  props: {
                    label: 'equipment_name',
                    value: 'equipment_no',
                  },
                  span: 24,
                },
                // {
                //   label: "模具数量",
                //   prop: "mouldNum",
                //   maxlength: 5
                // }
              ],
            },
          },
          {
            label: '设备清单',
            prop: 'prdList',
            slot: true,
            minWidth: 120,
            span: 24,
            display: false,
          },
          {
            label: '模具清单',
            prop: 'mouldList',
            slot: true,
            minWidth: 120,
            span: 24,
            display: false,
          },
          {
            label: '检具清单',
            prop: 'prdProcedureFixtureList',
            // addDisplay: false,
            editDisplay: true,
            viewDisplay: true,
            slot: true,
            span: 24,
            type: 'select',
            filterable: true,
            multiple: true,
            minWidth: 120,
            dicData: [],
            props: {
              label: 'label',
              value: 'checkToolNo',
            },
          },
        ],
      },
      data: [],
      form: {},
      goon: false,
      type: '',
      productList: [],
      procedureList: [],
    };
  },
  watch: {
    productId(newVal, oldVal) {
      if (newVal) {
        this.onLoad();
      }
    },
    'form.craftType'(newVal, oldVal) {
      if (newVal) {
        getProcessList({ craftType: newVal }).then((res) => {
          const column = this.findObject(this.option.column, 'procedureId');
          column.dicData = res.data.data;
          this.procedureList = res.data.data;
        });
      }
      if (oldVal) {
        this.$set(this.form, 'procedureId', '');
      }
    },
    'form.produceShopId'(newVal, oldVal) {
      if (newVal) {
        getLines({ shopId: newVal }).then((res) => {
          const data = res.data.data;
          const column = this.findObject(this.option.column, 'produceLineId');
          if (data.length > 0) {
            column.dicData = data;
          } else {
            column.dicData.length = 0;
            column.dicData = [];
          }
        });
        getGroupList(newVal).then((res) => {
          this.groupIdsList = res.data;
        });
      }
      if (oldVal) {
        this.form.produceLineId = null;
      }
    },
    'form.procedureId'(newVal, oldVal) {
      this.procedureList.every((item) => {
        if (item.id == newVal) {
          const column1 = this.findObject(this.option.column, 'produceBeat');
          const column2 = this.findObject(this.option.column, 'produceShopId');
          const column3 = this.findObject(this.option.column, 'produceLineId');
          if (item.outFlag == '2') {
            column1.rules = [];
            column2.rules = [];
            column3.rules = [];
          } else {
            column1.rules = [
              {
                required: true,
                message: '请输入生产节拍',
                trigger: 'blur',
              },
              {
                pattern: numFloor,
                message: '只能为正整数（不包含0）或最多两位小数',
                trigger: 'blur',
              },
            ];
            column2.rules = [
              {
                required: true,
                message: '请选择车间名称',
                trigger: 'blur',
              },
            ];
            column3.rules = [
              {
                required: true,
                message: '请选择生产线',
                trigger: 'blur',
              },
            ];
          }
          return false;
        } else {
          return true;
        }
      });
    },
  },
  computed: {
    ...mapGetters(['userInfo', 'permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.process_add, false),
        viewBtn: this.vaildData(this.permission.process_view, false),
        delBtn: this.vaildData(this.permission.process_remove, false),
        editBtn: this.vaildData(this.permission.process_edit, false),
      };
    },
  },
  created() {
    if (this.type == 'edit') {
      this.option.header = true;
      this.option.menu = true;
    } else {
      this.option.header = false;
      this.option.menu = false;
    }
  },
  mounted() {
    if (this.productId) {
      this.onLoad();
    }
  },
  methods: {
    equipmentChange(row) {
      for (let i = 0; i < this.equipmentOption.length; i++) {
        let item = this.equipmentOption[i];
        if (item.equipmentNo == row.equipmentNo) {
          this.form.prdProcedureEquipments[row.$index].mouldOption = item.mouldList.map((item) => {
            item.label = item.equipment_name + '(' + item.equipment_no + ')';
            return item;
          });
          break;
        }
      }
    },
    saveAndGoon() {
      this.$refs.crud.validate((res) => {
        if (res) {
          this.goon = true;
          this.$refs.crud.rowSave();
        } else {
          return false;
        }
      });
    },
    validFunction(row) {
      let equipMsg = '';
      if (row.prdProcedureEquipments.length > 0) {
        let equipments = [];
        row.prdProcedureEquipments.every((item, index) => {
          if (item.equipmentNo == '') {
            equipMsg = `【设备清单】第${index + 1}行 请选择设备名称`;
            this.$message.error(equipMsg);
            return false;
          } else {
            equipments.push(item.equipmentNo);
            return true;
          }
        });
        for (let i = 0; i < equipments.length; i++) {
          let itemi = equipments[i];
          for (let j = i + 1; j < equipments.length; j++) {
            let itemj = equipments[j];
            if (itemi == itemj) {
              equipMsg = `【设备清单】数据有重复，请修改`;
              this.$message.error(equipMsg);
              return false;
            }
          }
        }
        if (equipMsg) {
          return false;
        }
      }
      return true;
    },
    rowSave(row, done, loading) {
      // if (this.infoData.length == 0) {
      //   this.$message.warning('请添加工序信息');
      //   loading();
      //   return;
      // }
      // let content = this.infoData.map((item) => {
      //   item.productId = this.productId;
      //   return item;
      // });
      let valid = this.validFunction(row);
      if (!valid) {
        loading();
        return;
      }
      if (row.groupIds == '') {
        row.groupIds = [];
      }
      row.productId = this.productId;
      addProProcess(row).then(
        () => {
          if (this.goon) {
            loading();
            for (let key in this.$refs.crud.value) {
              this.$refs.crud.value[key] = null;
            };
            this.groupIdsList = []; //清空生产班组下拉选
            this.goon = false;
            // TODO: 如果要刷新列表，但不关闭窗口，需重新调用下onload方法即可
            this.onLoad();
          } else {
            this.onLoad();
            done();
          }
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        },
        (error) => {
          this.goon = false;
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      let valid = this.validFunction(row);
      if (!valid) {
        loading();
        return;
      }
      updateProProcess(row).then(
        () => {
          this.onLoad();
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return removeProProcess(row.id);
        })
        .then(() => {
          this.onLoad();
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return removeProProcess(this.ids);
        })
        .then(() => {
          this.onLoad();
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      this.type = type;
      this.dialogOpenType = type
      if (['edit', 'view'].includes(type)) {
        getProProcess(this.form.id).then((res) => {
          this.form = res.data.data;
          if (this.form.prdProcedureEquipments.length > 0) {
            this.form.prdProcedureEquipments = res.data.data.prdProcedureEquipments.map((item) => {
              this.equipmentOption.every((equip) => {
                if (item.equipmentNo == equip.equipmentNo) {
                  item.mouldOption = equip.mouldList.map((item) => {
                    item.label = item.equipment_name + '(' + item.equipment_no + ')';
                    return item;
                  });
                  return false;
                } else {
                  return true;
                }
              });
              return item;
            });
          }
        });
      } else {
        for (let k in this.form) {
          if (k == 'groupIds') {
            this.form[k] = [];
          } else {
            this.form[k] = '';
          }
        }
        this.$set(this.form, 'materialName', this.materialName);
        this.$set(this.form, 'innerDrawingNo', this.innerDrawingNo);
        this.$set(this.form, 'materialNo', this.materialNo);
      }
      done();
    },
    addSpanNumber() {
      const KEY_NAME = 'procedureId';
      const KEY_ROWSPAN = 'itemSpan';
      var k = 0;
      while (k < this.data.length) {
        this.data[k][KEY_ROWSPAN] = 1;
        for (var i = k + 1; i <= this.data.length - 1; i++) {
          if (this.data[k][KEY_NAME] === this.data[i][KEY_NAME] && this.data[k][KEY_NAME] !== '') {
            this.data[k][KEY_ROWSPAN]++;
          } else {
            break;
          }
        }
        k = i;
      }
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.query.productId = this.productId;
      getProProcessList(Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.data = data;
        this.addSpanNumber();
        this.loading = false;
        this.selectionClear();
      });
      getEquipmentList({ productId: this.productId }).then((res) => {
        this.equipmentOption = res.data.data.map((item) => {
          item.label = item.equipmentName + '(' + item.equipmentNo + ')';
          return item;
        });
      });
      getProdFixtureList({ productId: this.productId }).then((res) => {
        const column = this.findObject(this.option.column, 'prdProcedureFixtureList');
        column.dicData = res.data.data.map((item) => {
          item.label = item.checkToolName + '(' + item.checkToolNo + ')';
          return item;
        });
      });
      getWorkshopList().then((res) => {
        const column = this.findObject(this.option.column, 'produceShopId');
        column.dicData = res.data.data;
      });
    },
  },
};
</script>

<style lang="scss">
.processTable {
  .prdList {
    display: flex;
    flex-direction: column;
  }
  .prdItem {
    height: 23px;
    overflow: hidden;
    border-bottom: 1px solid #dce4f0;
    &:last-child {
      border-bottom: none;
    }
  }
}
</style>
